package com.substation.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bean.LoginInfo;
import com.bumptech.glide.Glide;
import com.greenentity.DataDictionary;
import com.greenentity.Defect;
import com.greenentity.Eqpt;
import com.greenentity.Inspect;
import com.greenentity.Photo;
import com.greenentity.Task;
import com.greenentity.Unit;
import com.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.previewlibrary.GPreviewBuilder;
import com.substation.R;
import com.substation.greendao.DataDictionaryDao;
import com.substation.greendao.DefectDao;
import com.substation.ui.utils.BitmapDrawTextUtils;
import com.substation.ui.utils.RecyclerViewUtils;
import com.substation.ui.utils.XUtils;
import com.substation.utils.DateUtils;
import com.substation.utils.DialogUtils;
import com.substation.utils.GreenDaoManager;
import com.substation.utils.SPUtils;
import com.substation.utils.TestingUtils;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import dmax.dialog.SpotsDialog;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class DefectAddActivity extends BaseListActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.list)
    RecyclerView list;
    SuperAdapter<String> adapter;
    List<String> datas = new ArrayList<>();
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.eqpt)
    TextView eqpt;
    @BindView(R.id.spinner1)
    Spinner spinner1;
    @BindView(R.id.content)
    EditText content;
    @BindView(R.id.choiseTxt)
    TextView choiseTxt;
    List<DataDictionary> defectLv;//缺陷等级
    String defectCode, defectValue;
    Unit unit;
    Eqpt e;

    @Override
    protected int getMyListLayoutId() {
        return R.layout.activity_defect_add;
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return RecyclerViewUtils.getLinearLayoutManagerForHorizontal(context);
    }

    @Override
    protected void initView() {
        super.initView();
        String unitContent = (String) SPUtils.get(context, "unit", "");
        content.setText((String) SPUtils.get(context, "defect_content", "") + "异常");
        unit = JSON.parseObject(unitContent, Unit.class);
        // 自定义图片加载器
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
        datas.add("");
        adapter.setData(datas);
        refresh.setEnabled(false);
        time.setText(DateUtils.getNewTime());
        defectLv = GreenDaoManager.getInstance().getmDaoSession().getDataDictionaryDao().queryBuilder().where(DataDictionaryDao.Properties.Type.eq("defect_level")).list();
        defectCode = defectLv.get(0).getCode();
        defectValue = defectLv.get(0).getValue();
        List<String> mItems = XUtils.dataDictionary2String(defectLv);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_txt, mItems);
        adapter.setDropDownViewResource(R.layout.spinner_txt);
        spinner1.setAdapter(adapter);
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                defectCode = defectLv.get(i).getCode();
                defectValue = defectLv.get(i).getValue();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        if (unit.getEqptGuid() == null || unit.getEqptGuid().equals("")) {
            eqpt.setText(unit.getTourUnit());
            e = new Eqpt();
            eqpt.setClickable(false);
        }
    }

    @Override
    protected void initData() {
        toolbar.setTitle(unit.getTourUnit() + "缺陷添加");
    }

    @Override
    public SuperAdapter getAdapter() {
        return adapter = new SuperAdapter<String>(R.layout.content_imge_horizontal) {
            @Override
            public void bindView(ViewHolder viewHolder, String s, final int i) {
                ImageView imageView = viewHolder.getView(R.id.imageView);
                ImageButton imageButton = viewHolder.getView(R.id.imageButton);
                if (i == datas.size() - 1) {
                    imageButton.setVisibility(View.GONE);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    Glide.with(context).load(R.mipmap.add_img).into(imageView);
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            if (e == null) {
                                showMsg("请先选择设备");
                                return;
                            }
                            XUtils.choiseImg(DefectAddActivity.this, 9 - datas.size() + 1);
                        }
                    });
                } else {
                    imageButton.setVisibility(View.VISIBLE);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    Glide.with(context).load(s).into(imageView);
                    imageView.setClickable(false);
                    imageButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            datas.remove(i);
                            adapter.notifyDataSetChanged();
                        }
                    });
                    viewHolder.getView(R.id.imageView).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            GPreviewBuilder.from(DefectAddActivity.this)
                                    .setData(XUtils.String2Image(datas))
                                    .setCurrentIndex(i)
                                    .setSingleFling(false)//是否在黑屏区域点击返回
                                    .setDrag(false)//是否禁用图片拖拽返回
                                    .setType(GPreviewBuilder.IndicatorType.Number)//指示器类型
                                    .start();//启动
                        }
                    });
                }
            }
        };
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_save, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.upload:
                if (e == null) {
                    showMsg("请先选择所属设备");
                    return true;
                }
                if (datas.size() == 1) {
                    showMsg("请上传照片");
                    return true;
                }
                String des = content.getText().toString();
                if (!TestingUtils.isEmpty(context, des, "缺陷描述")) return true;
                Task task = JSON.parseObject((String) SPUtils.get(context, "task", ""), Task.class);
                Defect defect = new Defect();
                defect.setDefectId(System.currentTimeMillis());
                defect.setWorkGuid(task.getWorkGuid());
                defect.setDefectDesc(des);
                defect.setEqptGuid(e.getEqptGuid() == null ? "" : e.getEqptGuid());
                defect.setUnitGuid(unit.getUnitGuid());
                defect.setTplUnitId(unit.getTplUnitId());
                defect.setDiscoveryUserId(LoginInfo.getInfo(context).getAccountProfileDetails().getObjectId());
                defect.setDiscoveryUserIdvalue(LoginInfo.getInfo(context).getAccountProfileDetails().getNickname());
                defect.setSubsGuid(task.getSubsGuid());
                defect.setDefectTime(DateUtils.getNewTime());
                defect.setDefectStatus("10");
                defect.setDefectGuid(UUID.randomUUID().toString());
                defect.setDefectLevel(defectCode);
                defect.setDefectLevelvalue(defectValue);
                defect.setDefectFrom("新增");
                if (getIntent().getBooleanExtra("inspect", false)) {
                    Inspect inspect = JSON.parseObject((String) SPUtils.get(context, "inspect", ""), Inspect.class);
                    inspect.setDefectCount(inspect.getDefectCount() + 1);
                    GreenDaoManager.getInstance().getmDaoSession().getInspectDao().update(inspect);
                    defect.setInspectGuid(inspect.getItemGuid());
                }
                GreenDaoManager.getInstance().getNewSession().insert(defect);
                datas.remove(datas.size() - 1);
                for (String s : datas) {
                    Photo photo = new Photo();
                    photo.setPhotoId(System.currentTimeMillis());
                    photo.setPhotoGuid(UUID.randomUUID().toString());
                    photo.setDefectGuid(defect.getDefectGuid());
                    photo.setPhAdd(s);
                    photo.setPhState("新增");
                    photo.setPhName(s.substring(s.lastIndexOf("/") + 1));
                    GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().insert(photo);
                }
                finish();
                return true;
            case android.R.id.home:
                DialogUtils.showMsgDialog(context, "是否返回", "您还未保存？是否直接退出？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == XUtils.REQUEST_CODE && resultCode == RESULT_OK && data != null) {// 图片选择结果回调
            List<String> pathList = data.getStringArrayListExtra("result");
            if (e == null) {
                showMsg("请先选择设备");
                return;
            }
            final SpotsDialog dialog = new SpotsDialog(context, "正在添加水印...");
            dialog.show();
            Observable.just(pathList).subscribeOn(Schedulers.io()).map(new Func1<List<String>, List<String>>() {
                @Override
                public List<String> call(List<String> list) {
                    return BitmapDrawTextUtils.createWater(context, (String) SPUtils.get(context, "substations", "") + " (缺陷照片)"
                            , TextUtils.isEmpty(e.getEqptName()) ? unit.getTourUnit() : e.getEqptName(), DateUtils.getNewTime(), list);
                }
            }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<String>>() {
                @Override
                public void call(List<String> list) {
                    dialog.dismiss();
                    dialog.cancel();
                    datas.remove(datas.size() - 1);
                    datas.addAll(list);
                    if (datas.size() <= 8) {
                        datas.add("");
                    }
                    adapter.notifyDataSetChanged();
                }
            });
        }
    }

    @OnClick(R.id.eqpt)
    public void onViewClicked() {
        DialogUtils.showEqpt(context, unit, new ResponseListener<Eqpt>() {
            @Override
            public void response(Eqpt data) {
                e = data;
                eqpt.setText(e.getEqptName());
                Task task = JSON.parseObject((String) SPUtils.get(context, "task", ""), Task.class);
                List<Defect> defects = GreenDaoManager.getInstance().getmDaoSession().getDefectDao().queryBuilder().where(DefectDao.Properties.WorkGuid.eq(task.getWorkGuid()), DefectDao.Properties.EqptGuid.eq(data.getEqptGuid())).list();
                if (defects.size() > 0) {
                    int count = 0;
                    String result = "";
                    for (Defect defect : defects) {
                        count++;
                        result += "\n<第" + count + "条缺陷>,缺陷描述:" + defect.getDefectDesc();
                    }
                    showMsg("该设备已有" + count + "条缺陷:" + result);
                }
            }
        });
    }
}
